<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 详情接口
 *
 * @author      Eden
 * @datetime    2016/12/1 22:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Detail_Model extends API_Model
{

    // 参数
    private $params;

    private $width = 320;
    private $height = 180;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {

            if (!$this->checkParams()) {
                $send['error'] = $this->getError();
                break;
            }

            $detail = $this->getDetail();
            if (!$detail) {
                $send['error'] = $this->getError();
                break;
            }

            $detail['addressInfo'] = $this->getAddress($detail['addressId']);

            $send['state'] = true;
            $send['data'] = $detail;
        } while(false);
        $this->output->send($send);
    }

    /**
     * 获取收货人信息
     * @param $addressId
     * @return array
     */
    protected function getAddress($addressId)
    {
        $add = array(
            'name' => '',
            'phone' => '',
            'address' => ''
        );
        if (empty($addressId)) {
            return $add;
        }

        $addDb = clone($this->db);
        $query = $addDb->get_where('user_address', array('id' => $addressId));
        $result = $query->row_array();
        if (!$result) {
            return $add;
        }

        $add['name'] = value($result, 'name');
        $add['phone'] = value($result, 'phone');
        $add['address'] = sprintf('%s %s %s %s', $result['province'], $result['city'], $result['area'], $result['address']);
        return $add;
    }

    /**
     * 商品详情
     * @return array|bool
     */
    protected function getDetail()
    {
        $orderId = $this->params['orderId'];
        try {
            $orderDb = clone($this->db);
            $query = $orderDb->get_where('user_order', array('id' => $orderId));
            $row = $query->row_array();
            if (empty($row)) {
                $this->setError('该订单不存在');
                return false;
            }

            $goodsDb = clone($this->db);
            $query = $goodsDb->select('uog.num, uog.price, uog.orderId, uog.goodsId, sg.goodsName, sg.streamId, sg.baseId, sg.thumb, sg.bannerThumb, sg.liveUrl, sg.expressWeight, sg.status')
                ->where_in('uog.orderId', $orderId)
                ->from('user_order_goods as uog')
                ->join('base_goods as sg', 'sg.id = uog.goodsId')
                ->get();
            $results = $query->result_array();
            $this->load->library('core/upload', null, 'up');
            $items = array();
            if ($results && is_array($results)) foreach($results as $item) {
                $thumb = !empty($item['bannerThumb']) ? $item['bannerThumb'] : $item['thumb'];
                $goodsItem = array(
                    'goodsId' => (int) value($item, 'goodsId'),
                    'goodsName' => value($item, 'goodsName'),
                    'num' => (int) value($item, 'num'),
                    'price' => doubleval($item['price']),
                    'thumb' => thumb($thumb, $this->width, $this->height),
                    'expressWeight' => doubleval($item['expressWeight']),
                    'status' => $item['status'] == 1 ? 'onSale' : 'offSale',
                    'isLive' => !empty($item['liveUrl']),
                    'liveUrl' => value($item, 'liveUrl', '')
                );
                $items[] = $goodsItem;
            }

            $goods = $row;
            $returns = array();
            $returns['orderId'] = (int) $goods['id'];
            $returns['sn'] = value($goods, 'sn');
            $returns['totalPrice'] = doubleval($goods['totalPrice']);
            $returns['goodsPrice'] = doubleval($goods['goodsPrice']);
            $returns['expressPrice'] = doubleval($goods['expressPrice']);
            $returns['voucher'] = doubleval($goods['voucher']);
            $returns['payMode'] = value($goods, 'payMode', 'online');
            $returns['addressId'] = (int) value($goods, 'addressId');
            $returns['created'] = value($goods, 'created');
            $returns['distribution'] = $this->getExpress($orderId);
            $returns['status'] = value($goods, 'status');
            $returns['goods'] = $items;
            $returns['message'] = value($goods, 'message', '');
            $results['isLive'] = !empty($goods['liveUrl']);
            $returns['liveUrl'] = value($goods, 'liveUrl', '');

            return $returns;

        } catch (PDOException $e) {
            $this->setError('订单获取失败');
        }
        return false;
    }

    /**
     * 快递
     * @param $orderId
     * @return mixed
     */
    public function getExpress($orderId)
    {
        $return['expressNo'] = '';
        $return['expressName'] = '';
        $return['expressTime'] = '';
        $query = $this->db->get_where('user_order_express', array('orderId' => $orderId));
        $row = $query->row_array();
        if ($row) {
            $return['expressNo'] = value($row, 'expressNo');
            $return['expressName'] = value($row, 'expressName');
            $return['expressTime'] = value($row, 'created');
        }
        return $return;
    }

    /**
     * 验证参数
     * @return bool
     */
    public function checkParams()
    {
        if (empty($this->params['orderId'])){
            $this->setError('参数错误');
            return false;
        }
        return true;
    }
}
